package xuli.dao.impl;

import entity.Order_Cart;
import entity.Product_Comment;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import util.C3P0Util;
import xuli.dao.ShoppingCartDao;

import java.sql.SQLException;
import java.util.List;

public class ShoppingCartDaoImpl implements ShoppingCartDao {

    private QueryRunner queryRunner = new QueryRunner(C3P0Util.getDataSource());

    @Override
    public boolean insert(Order_Cart orderCart) {
        int update = 0;
        try {
            update = queryRunner.update("insert into order_cart(user_id,product_id,product_amount,price,add_time,modified_time,model_id) values(?,?,?,?,?,?,?)", orderCart.getUser_id(), orderCart.getProduct_id(), orderCart.getProduct_amount(), orderCart.getPrice(), orderCart.getAdd_time(), orderCart.getModified_time(), orderCart.getModel_id());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update == 1;
    }


    @Override
    public boolean update(Order_Cart orderCart) {
        int update = 0;
        try {
            update = queryRunner.update("update order_cart set product_amount = ?,modified_time = ? where cart_id = ?", orderCart.getProduct_amount(), orderCart.getModified_time(),orderCart.getCart_id());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update == 1;
    }


    @Override
    public List<Order_Cart> findAll(Integer userId) {
        String sql = "select * from order_cart where user_id=?";
        List<Order_Cart> orderCarts = null;

        try {
            orderCarts = queryRunner.query(sql, new BeanListHandler<>(Order_Cart.class), userId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orderCarts;
    }


    @Override
    public Order_Cart findByUserIdAndProductIdAndModelId(Integer userId, Integer productId, Integer modelId) {
        String sql = "select * from order_cart where user_id=? and product_id = ? and model_id = ?";
        Order_Cart orderCarts = null;

        try {
            orderCarts = queryRunner.query(sql, new BeanHandler<>(Order_Cart.class), userId, productId, modelId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orderCarts;
    }

}
